<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/jquery-3.3.1.min.js"></script>
</head>
<body>
Welcome<br/>
<select id="select">
</select>
<input id="text" type="text"/>
<button onclick="send()">发送</button>
<button onclick="sendAll()">发给所有人</button>
<button onclick="closeWebSocket()">关闭</button>
<a href="/login">注销</a>
<div id="message">
</div>
</body>
<script type="text/javascript">
    $(function () {

    });

    //从url参数中获得数据
    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    var websocket = null;

    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        //初始化WebSocket
        websocket = new WebSocket("ws://192.168.10.52:8087/websocket/" + getQueryString("username"));
    }
    else {
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        setMessageInnerHTML("open");
    };

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        if (data.code == 1) {
            //为1时显示消息
            setMessageInnerHTML(data.message);
        } else {
            //为0时返回用户列表，刷新下拉框中的数据
            $("#select").html("");
            $.each(data.message, function (index, value) {
                $("#select").append("<option value='" + value + "'>" + value + "</option>");
            })
        }

    };

    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("close");
    };

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    };

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //私聊
    function send() {
        var message = document.getElementById('text').value;
        var object = {};
        object.code = 1;
        object.username = $("#select").val();
        object.message = message;
        websocket.send(JSON.stringify(object));
    }

    //群聊
    function sendAll() {
        var message = document.getElementById('text').value;
        var object = {};
        object.code = 0;
        object.username = $("#select").val();
        object.message = message;
        websocket.send(JSON.stringify(object));
    }
</script>
</html>